package cn.cuit.controller;

import cn.cuit.domain.Employee;
import cn.cuit.service.EmployeeService;
import cn.cuit.utils.AjaxResult;
import cn.cuit.utils.EmpQuery;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 员工管理接口
 * 要求前后端传递参数统一使用json格式
 * 写接口的三要素：
 *  1.请求地址是什么
 *  2.请求参数是什么
 *  3.返回值是什么
 */
@CrossOrigin//允许跨域
@RequestMapping("/employee")
@RestController
public class EmployeeController {
    //注入service接口
    @Autowired
    private EmployeeService employeeService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public List<Employee> getEmployees() {
        List<Employee> list = employeeService.list();
        return list;
    }

    /**
     * 分页查询
     * @param empQuery
     * @return
     */
    @PostMapping
    public Page<Employee> getEmployeePage(@RequestBody EmpQuery empQuery) {
        System.out.println(empQuery);
        //条件构造器
        QueryWrapper<Employee> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("addr", empQuery.getAddress()).like("name", empQuery.getName());
        //传入前端参数得到 page对象
        Page<Employee> employeePage = new Page<>(empQuery.getPageIndex(), empQuery.getPageSize());
        //执行分页查询
        Page<Employee> page = employeeService.page(employeePage,queryWrapper);
        return page;
    }
    /**
     * 查询单个
     * @param id
     * @return
     */
    @GetMapping("/{id}")//http://localhost:8080/employee/2
    public Employee getEmployee(@PathVariable("id") int id) {
        Employee byId = employeeService.getById(id);
        return byId;
    }

    /**
     * 新增或者修改
     * 根据id决定
     * @param employee
     * @return
     */
    @PutMapping//http://localhost:8080/employee
    public AjaxResult addOrUpdateEmployee(@RequestBody Employee employee) {//@RequestBody 将前端的json对象转化为实体对象
        if (employeeService.saveOrUpdate(employee)){
            return AjaxResult.me();
        }
        return AjaxResult.me().setSuccess(false).setMessage("程序错误，请联系管理员！");
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult deleteEmployee(@PathVariable("id") int id) {
        if (employeeService.removeById(id)){
            return AjaxResult.me();
        }
        return AjaxResult.me().setSuccess(false).setMessage("删除失败，请联系管理员！");
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping("/batchDelete")
    public AjaxResult batchDeleteEmployee(@RequestBody List<Integer> ids) {
        if (employeeService.removeByIds(ids)){
            return AjaxResult.me().setMessage("批量删除成功！");
        }
        return AjaxResult.me().setSuccess(false).setMessage("删除失败，请联系管理员！");
    }
}
